package com.chuanqi.admin.controller; 

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.chuanqi.admin.domain.Resourse;
import com.chuanqi.admin.dto.ZtreeNode;
import com.chuanqi.admin.service.ResourceService;

@Controller
@RequestMapping("/authc/resource")
public class AdminResourceController {

    @Autowired
    private ResourceService resourceService;
    
    @RequestMapping(value = "/getResourcesJsonByRoleId/{roleId}", method = RequestMethod.POST, produces="application/json")
    public @ResponseBody List<Map<String,Object>> resourceTreeJson(@PathVariable("roleId") Long roleId){	
    	List<Resourse> allResourse = resourceService.findAll();		
    	List<Resourse> permitedResources = resourceService.getResourceIdsByRoleId(roleId);
    	
    	List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
    	List<ZtreeNode> ztreeNodeList = new ArrayList<ZtreeNode>();	
    	
		for(Resourse resource: allResourse){
			ZtreeNode ztreeNode = new ZtreeNode(resource.getId(), resource.getParentId(), resource.getName(), true, false);	
			for (Resourse permitedResource : permitedResources) { 					
				if(resource.getId().intValue() == permitedResource.getId().intValue()){
					 ztreeNode = new ZtreeNode(resource.getId(), resource.getParentId(), resource.getName(), true, true);
					 break;
	        	}					
			}
			ztreeNodeList.add(ztreeNode);
		}	
		
		for(ZtreeNode zNode: ztreeNodeList){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", zNode.getId());
			map.put("pId", zNode.getpId());
			map.put("name", zNode.getName());
			map.put("open", zNode.getOpen());
			if(zNode.getChecked()){
				map.put("checked", true);				
			}
			
			mapList.add(map);
		}
		
		return mapList;    	
	}     
    
}

